﻿using FluentScheduler;
using OddUserManager.Data.Repositories;
using OddUserManager.Model;
using OddUserManager.Service.IServices;
using OddUserManager.Service.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OddUserManager.Web.Common
{
    public class SettlementOddJob : IJob
    {
        private readonly object _lock = new object();
        IOddService _oddService;
        IRealTimeJCMatchService _realTimeJCMatchService;
        IOddUserService _userService;

        public SettlementOddJob() { }
        //public SettlementOddJob(IOddService oddService, IRealTimeJCMatchService realTimeJCMatchService) {
        //    _oddService = oddService;
        //    _realTimeJCMatchService = realTimeJCMatchService;
        //}
        public void Execute()
        {
            lock (_lock)
            {
                _oddService = new OddService(new OddRepository());
                _realTimeJCMatchService = new RealTimeJCMatchService(new RealTimeJCMatchRepository());
                _userService = new OddUserService(new OddUserRepository());
                //获取所有未计算投注结果的投注单
                var unfinishedOdds = _oddService.GetUnfinishedOdds();
                var oddContents = new List<BetDetailOddContents>();

                unfinishedOdds.ForEach(p =>
                {
                    if (null != p.BetDetailOddList)
                    {
                        p.BetDetailOddList.ForEach(x =>
                        {
                            if (null != x.BetDetailOddContentsList)
                            {
                                oddContents.AddRange(x.BetDetailOddContentsList);
                            }
                        });
                    }
                });
                //获取有关的所有比赛的ID，然后查询出比赛详细信息
                var matchIds = oddContents.Select(p => p.SelectedMatchId).Distinct().ToList();
                if (matchIds.Count == 0)
                {
                    return;
                }
                var matchs = _realTimeJCMatchService.GetMatchsByIds(matchIds);

                for (var i = 0; i < unfinishedOdds.Count; i++)
                {
                    var o = unfinishedOdds[i];
                    if (null == o.BetDetailOddList) { continue; }
                    CheckOddWinOrNot(ref o, matchs);
                    _oddService.InsertOrUpdateOdd(o);
                }
            }
        }



        private void CheckOddWinOrNot(ref Odd o, List<JCMatch> matchs)
        {
            List<LotteryResults> allRsults = new List<LotteryResults>();

            foreach (var c in o.BetDetailOddList)
            {
                var oddValue = 1m;
                if (null == c.BetDetailOddContentsList) { continue; }
                foreach (var d in c.BetDetailOddContentsList)
                {
                    var match = matchs.SingleOrDefault(p => p.MatchId == d.SelectedMatchId);

                    if (null != match)
                    {
                        //如果比赛已经完结并且 投注单这个选项并没有结算结果.那么就计算中奖结果
                        if (match.SellingStatus == "已完成" && match.WholeScore.Length > 0)
                        {
                            var results = match.WholeScore.Split(":");
                            var fix = int.Parse(d.FixOdds == "" ? "0" : d.FixOdds);
                            var r = int.Parse(results[0]) - int.Parse(results[1]) + fix;
                            var r2 = -9999;
                            if (!string.IsNullOrEmpty(match.HalfCourtScore) && match.HalfCourtScore != ":")
                            {
                                var halfResult = match.HalfCourtScore.Split(":");
                                r2 = int.Parse(halfResult[0]) - int.Parse(halfResult[1]) + fix;
                            }


                            if ((d.SelectedResult == SelectedResult.胜 && r > 0)
                                || (d.SelectedResult == SelectedResult.平 && r == 0)
                                || (d.SelectedResult == SelectedResult.负 && r < 0)
                                || (d.SelectedResult == SelectedResult.让球胜 && r > 0)
                                || (d.SelectedResult == SelectedResult.让球平 && r == 0)
                                || (d.SelectedResult == SelectedResult.让球负 && r < 0)
                                )
                            {
                                d.LotteryResults = LotteryResults.已中奖;
                                oddValue = oddValue * d.SelectedOdds;
                            }
                            else if ((d.SelectedResult == SelectedResult.胜胜 && r > 0 && r2 > 0)
                                || (d.SelectedResult == SelectedResult.负负 && r < 0 && r2 < 0 && r2 != -9999))
                            {
                                d.LotteryResults = LotteryResults.已中奖;
                                oddValue = oddValue * d.SelectedOdds;
                            }
                            else
                            {
                                d.LotteryResults = LotteryResults.未中奖;
                            }
                        }
                    }
                }
                var oResults = c.BetDetailOddContentsList.Select(p => p.LotteryResults).ToList();
                allRsults.AddRange(oResults);
                c.LotteryResults = CheckWinOrNot(oResults);

                if (c.LotteryResults == LotteryResults.已中奖)
                {
                    c.Bonus = c.BetCount * (Math.Round(oddValue * 2, 2));
                }
                else
                {
                    c.Bonus = 0;
                }
            }
            var osResults = o.BetDetailOddList.Select(p => p.LotteryResults).ToList();
            o.Result = CheckOddWinOrNot(osResults);
            if (allRsults.Contains(LotteryResults.未开奖) && !allRsults.Contains(LotteryResults.已中奖) && !allRsults.Contains(LotteryResults.未中奖))
            {
                o.State = OddState.已上传;
            }
            else if (allRsults.Contains(LotteryResults.未开奖) && (allRsults.Contains(LotteryResults.已中奖) || allRsults.Contains(LotteryResults.未中奖)))
            {
                o.State = OddState.比赛中;
            }
            else if (!allRsults.Contains(LotteryResults.未开奖))
            {

                var money = 0m;
                if (o.OwnBonus == 0)
                {
                    if (o.BetDetailOddList.Sum(p => p.Bonus) > 0)
                    {
                        money = o.BetDetailOddList.Sum(p => p.Bonus);
                        //如果投注中奖就把奖金加入到账号里
                        //var oddUser = _userService.GetUserById(o.CreateOddUserId);
                        //oddUser.AccountBalance += o.BetDetailOddList.Sum(p => p.Bonus);
                        //_userService.InsertOrUpdateUser(oddUser);
                    }
                }
                else
                {
                    if (o.BetDetailOddList.Sum(p => p.Bonus) != o.OwnBonus)
                    {
                        money = o.BetDetailOddList.Sum(p => p.Bonus) - o.OwnBonus;
                    }
                }
                //2018-05-13 废除自动把奖金加入到账户余额,改为人工加入
                //if (money != 0)
                //{
                //    //如果投注中奖就把奖金加入到账号里
                //    var oddUser = _userService.GetUserById(o.CreateOddUserId);
                //    oddUser.AccountBalance += money;
                //    _userService.InsertOrUpdateUser(oddUser);
                //}
                o.State = OddState.待确认;
                o.OwnBonus = o.BetDetailOddList.Sum(p => p.Bonus);

                if (DateTime.Now < o.LotteryTime)
                {
                    o.LotteryTime = DateTime.Now;
                }
            }
        }



        /// <summary>
        /// 判断是否中奖
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        private LotteryResults CheckWinOrNot(List<LotteryResults> results)
        {
            LotteryResults result = LotteryResults.未开奖;
            if (results.Contains(LotteryResults.未开奖))
            {
                result = LotteryResults.未开奖;
            }
            else if (!results.Contains(LotteryResults.未开奖) && !results.Contains(LotteryResults.未中奖))
            {
                result = LotteryResults.已中奖;
            }
            else
            {
                result = LotteryResults.未中奖;
            }
            return result;
        }

        //判断整个投注单是否中奖
        private LotteryResults CheckOddWinOrNot(List<LotteryResults> results)
        {
            LotteryResults result = LotteryResults.未开奖;
            if (results.Contains(LotteryResults.未开奖))
            {
                result = LotteryResults.未开奖;
            }
            else if (!results.Contains(LotteryResults.未开奖) && results.Contains(LotteryResults.已中奖))
            {
                result = LotteryResults.已中奖;
            }
            else if (!results.Contains(LotteryResults.未开奖) && !results.Contains(LotteryResults.已中奖))
            {
                result = LotteryResults.未中奖;
            }
            return result;
        }
    }
}
